package com.mobile.ado.util.ringtone;

import java.util.ArrayList;
import java.util.Calendar;

import android.content.Context;

import com.mobile.ado.setting.ringtone.TimeSpanRingtone;
import com.mobile.ado.util.Scheduler;

public class RingtoneScheduler extends Scheduler {

	private Context context;
	private ArrayList<TimeSpanRingtone> ringtones;

	public RingtoneScheduler(Context context,
			ArrayList<TimeSpanRingtone> ringtones) {
		this.context = context;
		this.ringtones = ringtones;
	}

	@Override
	public ArrayList<Long> getDelay() {
		ArrayList<Long> delays = new ArrayList<Long>();
		for (int i = 0; i < ringtones.size(); i++) {
			TimeSpanRingtone ringtone = ringtones.get(i);
			Calendar startTime = ringtone.getStartTime();
			Long delay = (startTime.getTimeInMillis() - Calendar.getInstance()
					.getTimeInMillis()) / 1000;
			delays.add(delay);
		}
		return delays;

	}

	@Override
	public ArrayList<Long> getPeriod() {
		ArrayList<Long> periods = new ArrayList<Long>();
		for (int i = 0; i < ringtones.size(); i++) {
			Long perioid = new Long(24 * 60 * 60);
			periods.add(perioid);
		}
		return periods;
	}

	@Override
	public ArrayList<Runnable> getTaksRunnable() {
		ArrayList<Runnable> runables = new ArrayList<Runnable>();
		for (int i = 0; i < ringtones.size(); i++) {
			runables.add(new RingtoneScheduleWorker(context, ringtones.get(i)));
		}
		return runables;
	}

	public void setCurrentRingtone() {
		TimeSpanRingtone currentRingtone = getCurrentRingtone();
		if (currentRingtone != null) {
			RingtoneUtils.setRingtone(context, currentRingtone.getAudioPath());
		}
	}

	private TimeSpanRingtone getCurrentRingtone() {
		TimeSpanRingtone ringTone = null;

		for (int i = 0; i < ringtones.size(); i++) {
			Calendar startTime = ringtones.get(i).getStartTime();
			Calendar endTime = ringtones.get(i).getEndTime();

			Calendar nowTime = Calendar.getInstance();
			nowTime.set(Calendar.AM_PM, 0);
			nowTime.set(Calendar.YEAR, startTime.get(Calendar.YEAR));
			nowTime.set(Calendar.MONTH, startTime.get(Calendar.MONTH));
			nowTime.set(Calendar.DAY_OF_MONTH, startTime
					.get(Calendar.DAY_OF_MONTH));

			if ((nowTime.after(startTime) || nowTime.equals(startTime))
					&& (nowTime.before(endTime) || nowTime.equals(endTime))) {
				ringTone = ringtones.get(i);
			}

		}
		return ringTone;
	}

}
